import os
import sys
import shutil
import fnmatch
import traceback

pattern = ''

def onerror(func, path, exc_info):
    os.chmod(path, 0600)
    func(path)
    return True

def rmtree(path, pattern):
    err = 0
    for fname in fnmatch.filter(os.listdir(path), pattern):
        fname = os.path.join(path, fname)
        print 'Removing', fname, '...',
        try:
            if os.path.isdir(fname):
                shutil.rmtree(fname, onerror=onerror)
            elif os.path.isfile(fname):
                os.chmod(fname, 0600)
                os.remove(fname)
            else:
                raise ValueError, fname
        except:
            print 'Failed.'
            traceback.print_exc()
            err = 1
        else:
            print 'OK.'
    return err

if __name__ == '__main__':
    assert len(sys.argv) > 1, 'Not enough arguments'
    path = sys.argv[1].decode('mbcs')
    path = os.path.abspath(os.path.expanduser(path))
    if len(sys.argv) == 2:
        pattern = os.path.basename(path)
        path = os.path.dirname(path)
    elif len(sys.argv) == 3:
        pattern = sys.argv[2]
    sys.exit(rmtree(path, pattern))
